package cn.itcast.web.controller;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    @RequestMapping(path = "/login", name = "用户登录")
    public String login(String email, String password) {
        // 根据邮箱查询数据库
        User loginUser = userService.findByEmail(email);
        // 判断邮箱是否存在
        if (loginUser == null) {
            request.setAttribute("error", "邮箱不存在");
            return "forward:/login.jsp";
        }


        // shiro认证代码 start
        // 1.将邮箱+密码封装到token
        String md5Pwd = new Md5Hash(password, email, 2).toString();
        UsernamePasswordToken token = new UsernamePasswordToken(email, md5Pwd);
        // 2.获取主体对象（工具类）
        Subject subject = SecurityUtils.getSubject();
        // 3.调用subject的登录方法
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            // 密码不正确
            request.setAttribute("error", "密码不正确");
            return "forward:/login.jsp";
        }
        // 4.从shiro中获取登录成功的user对象
         loginUser = (User) subject.getPrincipal();
        // 5.存储到session域
        session.setAttribute("loginUser", loginUser);
        // shiro认证代码 end


        // 查询动态菜单
        List<Module> modules = moduleService.findModuleListByUser(loginUser);
        session.setAttribute("modules", modules);
        return "home/main";
    }

    //退出
    @RequestMapping(path = "/logout", name = "用户登出")
    public String logout() {
        SecurityUtils.getSubject().logout();   //登出

        session.removeAttribute("loginUser");
        return "forward:/login.jsp";
    }

    @RequestMapping(path = "/home", name = "后台管理页面")
    public String main() {
        return "home/home";
    }
}
